package net.myspring.middle.web;

import net.myspring.common.domain.SearchEntity;
import net.myspring.common.utils.Message;
import net.myspring.common.utils.RequestUtils;
import net.myspring.middle.domain.Menu;
import net.myspring.middle.domain.Permission;
import net.myspring.middle.service.MenuService;
import net.myspring.middle.service.PermissionService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.stream.Collectors;

/**
 * Created by admin on 2016/8/10.
 */
@Controller
@RequestMapping(value = "sys/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private MenuService menuService;

    @RequestMapping(value = "list")
    @PreAuthorize("hasAnyAuthority('PERM_sys:permission:list:view')")
    public String list(Model model, HttpServletRequest request) {
        SearchEntity searchEntity = RequestUtils.getSearchEntity(request, Permission.class.getName());
        model.addAttribute("page", permissionService.findPage(searchEntity.getPageable(), searchEntity.getParams()));
        model.addAttribute("s", searchEntity);
        return "sys/permissionList";
    }

    @RequestMapping(value = "form")
    @PreAuthorize("hasAnyAuthority('PERM_sys:permission:list:edit')")
    public String form(Model model, Permission permission) {
        addAttribute(model);
        return "sys/permissionForm";
    }

    @RequestMapping(value = "save")
    @PreAuthorize("hasAnyAuthority('PERM_sys:permission:list:edit')")
    public String save(Model model, String data, RedirectAttributes redirectAttributes) {
        permissionService.save(data);
        redirectAttributes.addFlashAttribute("message", new Message("权限保存成功"));
        return "redirect:/sys/permission/list";
    }

    @RequestMapping(value = "checkSave")
    @ResponseBody
    public String checkSave(Model model, String data) {
        return permissionService.check(data);
    }

    private void addAttribute(Model model) {
        model.addAttribute("menus", menuService.findByType(Menu.MenuType.NAVIGATION.getValue()).stream().map(Menu::getName).collect(Collectors.toList()));
        model.addAttribute("data", permissionService.findAllData());
    }


}
